import Async from 'async'

export function getBookContent(bookId) {
    return fetch("/bookService/getBookContent",
        {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ bookId })
        }).then(res => res.json())
}

export function getBook(bookId) {
    return fetch("/bookService/getBook",
        {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ bookId })
        }).then(res => res.json())
}



export function getBooksByCategory(categoryId, page = 0, size = 1000) {
    return fetch("/bookService/getBooksByCategory",
        {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ categoryId, page, size })
        }).then(res => res.json()).then(json => json.content)
}

export function searchBooks(keyword, page = 0, size = 1000) {
    return fetch("/bookService/searchBooks",
        {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ keyword, page, size })
        }).then(res => res.json()).then(json => json.content)
}

var _getAllCategories_cache;
export function getAllCategories(callback) {
    if (_getAllCategories_cache) {
        callback(_getAllCategories_cache)
    } else {
        getCategories(0).then(categories => {
            Async.parallelLimit(categories.map(category => (callback) => {
                getCategories(category.categoryId).then(subCategories => {
                    category.children = subCategories
                    callback(null)
                })
            }), 10, (err) => {
                _getAllCategories_cache = categories
                callback(categories)
            })
        })
    }
}

export function getCategories(parentId) {
    return fetch("/bookService/getCategoryListByParent",
        {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ parentId })
        })
        .then(res => res.json())
}

export function getCategory(categoryId) {
    return fetch("/bookService/getCategory",
        {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ categoryId })
        })
        .then(res => res.json())
}


export function getRecommendationList() {
    return fetch("/recommendationService/getRecommendations", {
        method: 'POST', headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }, body: JSON.stringify({})
    })
        .then(res => res.json())
}